from django.shortcuts import render, redirect
from la import models
from la.views import UserInfoModelForm


def userinfo(req):
    """用户信息操作"""
    userinfos = models.userinfo.objects.filter(isty=1).all()
    return render(req, "userinfo.html", {"userinfos": userinfos})

# from django import forms
# class userinfo(forms.ModelForm):
#     class meta:
#         model = models.UserInfo

def userinfo_add(req):
    """用户信息添加操作"""
    storeinfos = models.storeinfo.objects.filter(id__gt=1).all()
    if req.method == "GET":
        form = UserInfoModelForm()
        return render(req, "userinfo_add.html", {"storeinfos": storeinfos, "form": form})

    # username = req.POST.get("name")
    # no = req.POST.get("no")
    # password = req.POST.get("password")
    # le = req.POST.get("le")
    # storecode = req.POST.get("storecode")
    # if le == "on":
    #     le = 0
    # else:
    #     le = 1
    # if storecode == None:
    #     storecode = 1;
    #
    # models.userinfo.objects.create(name=username, no=no, password=password, level=le, storecode_id=storecode, isty=1)
    form = UserInfoModelForm(data=req.POST)
    if form.is_valid():
        form.instance.isty = 1
        form.save()
        return redirect("/la/userinfo/")
    else:
        return render(req, "userinfo_add.html", {"storeinfos": storeinfos, "form": form})


def userinfo_edit(req, nid):
    """用户信息修改操作"""
    if req.method == "GET":
        userinfo = models.userinfo.objects.filter(id=nid).all().first()
        storeinfos = models.storeinfo.objects.filter(id__gt=1).all()
        form = UserInfoModelForm(instance=userinfo)
        return render(req, "userinfo_edit.html", {"userinfo": userinfo, "storeinfos": storeinfos, "form":form})

    # username = req.POST.get("name")
    # no = req.POST.get("no")
    # password = req.POST.get("password")
    # le = req.POST.get("le")
    # storecode = req.POST.get("storecode")
    # if le == "on":
    #     le = 0
    # else:
    #     le = 1
    # if storecode == None:
    #     storecode = 0;
    # models.userinfo.objects.filter(id=nid).update(name=username, no=no, password=password, level=le,
    #                                               storecode=storecode, isty=1)
    # return redirect("/la/userinfo/")
    userinfo = models.userinfo.objects.filter(id=nid).all().first()
    form = UserInfoModelForm(data=req.POST,instance=userinfo)
    if form.is_valid():
        form.instance.isty = 1
        form.save()
        return redirect("/la/userinfo/")
    else:
        return render(req, "userinfo_edit.html", {"form": form})


def userinfo_stop(req, nid):
    '''用户停用操作'''
    models.userinfo.objects.filter(id=nid).update(isty=0)
    return redirect("/la/userinfo/")


